const http = require('http');
const fs = require('fs');
const path = require('path');
const mimeModel = require('./model/getmime.js');

// console.log(mimeModel.getMime('.css'));

http.createServer((req, res)=>{
    let pathname = req.url;
    if(pathname == '/'){
        pathname = '/index.html';
    }

    //获取文件的后缀名
    let extname = path.extname(pathname);
    if(pathname != '/favicon.ico'){
        console.log(pathname);
        //获取static目录下的文件
        fs.readFile('static/' + pathname, (err, data)=>{
            if(err){
                console.log('404');
                fs.readFile('static/404.html', (error, data404)=>{
                    if(error){
                        console.log(error);
                    }
                    res.writeHead(404, {"Content-Type":"text/html;charset='utf-8'"});
                    res.write(data404);
                    res.end();
                });
            }
            else{
                //返回文件内容
                let mime = mimeModel.getMime(extname);
                res.writeHead(200, {"Content-Type":""+mime+";charset='utf-8'"});
                res.write(data);
                res.end();
            }
        });
    }
}).listen(8001);